import { useContext, useMemo, useState } from "react";

import { tableContext } from "@/layouts";
import { WarehouseState } from "@/pages/init_base/inventory/utils/columns";
import { BatchActions } from "@/shared/components/batch_actions";
import { usePaginationQuery } from "@/shared/hooks/use_pagination_query";
import { useTableSelection } from "@/shared/hooks/use_table_selection/use_table_selection";
import { ObjectType } from "@/shared/typings";
import { ExclamationCircleFilled } from "@ant-design/icons";
import { history, useLocation, useModel } from "@umijs/max";
import { useRequest } from "ahooks";
import { Button, Divider, Input, Modal, Space, message } from "antd";
import { useEffect } from "react";
import { TableProps, TableReturn } from "../typings";
import React = require("react");
import useManageForm from "../use_manage_form";
const { TextArea } = Input;

/** 会有一些业务逻辑，不会开放得特别灵活，那就跟单独写没区别了 */
export default function useRelationTable<T extends ObjectType>({
  title,
  currentId,
  queryListIdKey = "id",
  nodeIdKey = "warehouse_id",
  batchSubmitKey = "ids",
  submitKey = "warehouse",
  columns,
  listApi,
  updateList,
  batchUpdateApi,
  batchDeleteApi,
  moduleKey,
  diyConfig,
  action = [
    "编辑",
    "删除",
    "复制",
    {
      name: ["启用"],
      restParms: ["1"],
      fn: (selectedRowKeys, ...rest) => {
        console.log(rest, "操作方法提供的额外参数");
        return {
          sub: {
            filter: { [batchSubmitKey]: selectedRowKeys! } as any,
            new_state: 1 ? 2 : 3,
          },
        };
      },
    },
    {
      name: "审核",
      restParms: "1",
      fn: (selectedRowKeys, ...rest) => {
        console.log(rest, "操作方法提供的额外参数");
        return {
          sub: {
            filter: { [batchSubmitKey]: selectedRowKeys! } as any,
            new_state: 1 ? 2 : 3,
          },
        };
      },
    },
  ],
}: TableProps<T>): TableReturn {
  const { addressList } = useModel("global");
  const { pathname } = useLocation();
  const { setReload, reload } = useContext(tableContext)!;
  // const { addressLabel, setRowData } = useAddressLabel();
  const { search, tableProps, refresh } = usePaginationQuery<T>({
    service: listApi,
  });
  const [open, setOpen] = useState(false);

  const { renderManageForm } = useManageForm({
    defaultData: [],
    submitData: (value, submitType, form) => {
      const param = {
        ...value,
        addr_province_id: value?.$address?.addr?.[0],
      };
      // if (type !== 'edit') {} 可以加入一些变量改造符合业务
      runUpdateList({ warehouse: param }).then(() => {
        message.success("成功！");
      });
    },
  });

  const { runAsync: runBatchPutApi } = useRequest(batchUpdateApi, {
    manual: true,
  });
  const { runAsync: runUpdateList } = useRequest(updateList, { manual: true });

  const { rowSelection, isSelectedTotal, setIsSelectedTotal } =
    useTableSelection<T["warehouse_id"], T>({
      getRowKey: (data) => data[nodeIdKey],
      dataSource: tableProps.dataSource,
      tablePagination: {
        current: 1,
        pageSize: 20,
        total: 200,
      },
    });

  const handleButton = (selectedRowKeys?: React.Key[], ...rest) => {
    action.forEach((item) => {
      Modal.confirm({
        title: "确认提示",
        icon: <ExclamationCircleFilled />,
        content: "确认吗",
        onOk() {
          runBatchPutApi(item.fn(selectedRowKeys)).then(() => {
            message.success("操作成功！");
            refresh();
          });
        },
        onCancel() {},
      });
    });
  };

  const handleUpdateList = (record: T) => {
    runUpdateList({
      [submitKey]: {
        ...record,
        is_enabled: 1,
      },
    }).then(() => {
      message.success("修改成功！");
      refresh();
    });
  };

  const handleRefresh = () => {
    refresh();
    setIsSelectedTotal(false);
  };

  useEffect(() => {
    const params = { [queryListIdKey]: currentId };
    search({ ...params });
    setIsSelectedTotal(false);
  }, [currentId]);

  useEffect(() => {
    setReload({
      ...reload,
      [pathname]: () => refresh(),
    });
  }, []);

  const renderRelationTable = useMemo(() => {
    return (
      <>
        <div className="h-[56px] flex items-center justify-between">
          <div>
            <Space size="middle" className="ml-[10px]">
              <Button
                onClick={() =>
                  handleButton(rowSelection.selectedRowKeys, "enable")
                }
                size="small"
                type="primary"
                ghost
              >
                启用
              </Button>
              <Button
                onClick={() =>
                  handleButton(rowSelection.selectedRowKeys, "forbidden")
                }
                size="small"
                type="primary"
                ghost
              >
                禁用
              </Button>
              <Button
                onClick={() =>
                  handleButton(rowSelection.selectedRowKeys, "delete")
                }
                size="small"
                type="primary"
                ghost
              >
                删除
              </Button>
            </Space>
          </div>
          <Space size="middle">
            <Button onClick={handleRefresh}>刷新</Button>
            <Button
              onClick={() => history.push(`/stock_manage/${moduleKey}/create`)}
              type="primary"
            >
              {title}
            </Button>
          </Space>
        </div>

        <ProTable<T>
          size="small"
          rowKey={nodeIdKey}
          // 禁用了不能移动
          diyConfig={diyConfig}
          renderEmptyContent="-"
          {...tableProps}
          dataSource={(tableProps?.dataSource || []).map((k) => {
            /** 补充完整地址 */
            const currentProvince = addressList.find(
              (item) => item.value === k.addr_province_id
            );
            const currentCity = currentProvince?.children?.find(
              (item) => item.value === k.addr_city_id
            );
            const currentArea = currentCity?.children?.find(
              (item) => item.value === k.addr_area_id
            );
            // setRowData(k);
            // return {
            //   ...k,
            //   $completeAddress: !!currentProvince ? `${addressLabel.join('/')} ${k.address}` : '-',
            // };
            return {
              ...k,
              $completeAddress: !!currentProvince
                ? `${currentProvince?.label}/${currentCity?.label}/${currentArea?.label} ${k.address}`
                : "-",
            };
          })}
          rowSelection={rowSelection}
          columns={[
            ...columns,
            {
              title: "操作",
              dataIndex: "action",
              key: "action",
              fixed: "right",
              width: 180,
              render: (value, record) => {
                return (
                  <Space>
                    <Button
                      onClick={() =>
                        history.push(
                          `/stock_manage/${moduleKey}/edit/${record?.[nodeIdKey]}`
                        )
                      }
                      className="p-0"
                      type="link"
                    >
                      编辑
                    </Button>
                    <Divider type="vertical" />
                    <Button
                      onClick={() =>
                        // history.push(
                        //   `/stock_manage/${moduleKey}/copy/${record?.[nodeIdKey]}`
                        // )
                        setOpen(true)
                      }
                      className="p-0"
                      type="link"
                    >
                      复制
                    </Button>
                    <Divider type="vertical" />
                    <Button
                      onClick={() => handleUpdateList(record)}
                      className="p-0"
                      type="link"
                    >
                      {record.is_enabled === 1 ? "禁用" : "启用"}
                    </Button>
                  </Space>
                );
              },
            },
          ]}
          scroll={{ x: 1500, y: "calc(100vh - 320px)" }}
        />
        <Modal
          title="编辑表格"
          open={open}
          onOk={() => {}}
          onCancel={() => setOpen(false)}
        >
          <div className="flex my-[30px]">{renderManageForm}</div>
        </Modal>
      </>
    );
  }, [tableProps, rowSelection]);

  return {
    renderRelationTable,
  };
}
